package com.iflyings.android.dataconfig

object TypeUtils {

    fun <T> toString(data: T): String {
        return data.toString()
    }

    @Suppress("UNCHECKED_CAST")
    fun <T> toType(data: String?, defaultValue: T, clazz: Class<T>): T {
        val value = data ?: return defaultValue
        when (defaultValue) {
            is Boolean -> return (value == "true") as T
            is Int ->  return value.toInt() as T
            is Long -> return value.toLong() as T
            is Float -> return value.toFloat() as T
            is Double -> return value.toDouble() as T
            is String -> return value as T
        }
        if (clazz.isEnum) {
            val values = clazz.enumConstants as Array<out Enum<*>>
            for (v in values) {
                if (v.name == value) {
                    return v as T
                }
            }
            return defaultValue
        }

        return clazz.constructors.first {
            return@first (it.parameterTypes.size == 1 && it.parameterTypes[0] == String::class.java)
        }.apply {
            setAccessible(true)
        }.newInstance(value) as T
    }
}